package service

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"go_private_im/internal/comet/biz"
	"go_private_im/internal/comet/conf"
	"go_private_im/internal/comet/pkg"

	pb "go_private_im/api/comet"
)

type CometService struct {
	pb.UnimplementedCometServer
	uc *biz.CometUsecase
	log *log.Helper
	conf *conf.Config
}

func NewCometService(logger log.Logger,uc *biz.CometUsecase,conf *conf.Config) *CometService {
	return &CometService{
		uc: uc,
		conf: conf,
		log: log.NewHelper(logger),
	}
}

func (s *CometService) PushMsg(ctx context.Context, req *pb.PushMsgReq) (*pb.PushMsgReply, error) {
	if len(req.Keys) == 0 || req.Proto == nil {
		return nil, pkg.ErrPushMsgArg
	}
	pushMsg := biz.PushMsg{
		Keys: req.Keys,
		ProtoOp: req.ProtoOp,
		Proto: req.Proto,
	}
	if err := s.uc.PushMsg(ctx,&pushMsg); err != nil{
		return nil, err
	}
	return &pb.PushMsgReply{}, nil
}


func (s *CometService) Broadcast(ctx context.Context, req *pb.BroadcastReq) (*pb.BroadcastReply, error) {
	if req.Proto == nil {
		return nil, pkg.ErrBroadCastArg
	}

	broadcastMsg := &biz.BroadcastMsg{
		Speed: req.Speed,
		ProtoOp: req.ProtoOp,
		Proto: req.Proto,
	}
	if err := s.uc.Broadcast(ctx,broadcastMsg); err != nil{
		return nil, err
	}
	return &pb.BroadcastReply{}, nil
}
func (s *CometService) BroadcastRoom(ctx context.Context, req *pb.BroadcastRoomReq) (*pb.BroadcastRoomReply, error) {
	if req.Proto == nil || req.RoomId == "" {
		return nil, pkg.ErrBroadCastRoomArg
	}
	if err := s.uc.BroadcastRoom(ctx,req); err != nil{
		return nil, err
	}
	return &pb.BroadcastRoomReply{}, nil
}
func (s *CometService) Rooms(ctx context.Context, req *pb.RoomsReq) (*pb.RoomsReply, error) {
	Rooms := s.uc.Rooms(ctx)
	return &pb.RoomsReply{Rooms: Rooms.Rooms}, nil
}
func (s *CometService) AddRoom(ctx context.Context, req *pb.AddRoomReq) (*pb.AddRoomReply, error) {
	addRoom := &biz.AddRoom{
		Keys: req.Keys,
		RoomId: req.RoomId,
		Op: req.ProtoOp,
	}
	err := s.uc.UserAddRoom(ctx,addRoom)
	return &pb.AddRoomReply{}, err
}
func (s *CometService) OutRoom(ctx context.Context, req *pb.OutRoomReq) (*pb.OutRoomReply, error) {
	outRoom := &biz.OutRoom{
		Keys: req.Keys,
		RoomId: req.RoomId,
		Op: req.ProtoOp,
	}
	err := s.uc.UserOutRoom(ctx,outRoom)
	return &pb.OutRoomReply{}, err
}